package com.timesheet.server.core.models;

import com.timesheet.server.core.util.HibernateUtil;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class Main {

	private static SessionFactory factory;

	public static void main(String[] args) {

		Timesheet timesheet = new Timesheet();
		timesheet.setDescription("test description");

		timesheet.setTaskNo(104);
		timesheet.setTaskPhase("Coding");

		Timesheet newValue = new Timesheet();
		newValue.setDescription("new test task description");

		try {
			if (!findDuplicate(timesheet)) {
				save(timesheet);
			}
			else {
				System.out.println("Duplicate exists");
			}
		}
		catch (Exception exception) {
			exception.printStackTrace();
		}

	}

	public static boolean findDuplicate(Timesheet timesheet) {

		HibernateUtil hibenateUtil = new HibernateUtil();
		Session session = hibenateUtil.getSession();
		Query q =
				session.createQuery("from Timesheet timesheet where timesheet.taskNo = :taskNo AND timesheet.taskPhase=:taskPhase");
		q.setParameter("taskNo", timesheet.getTaskNo());
		q.setParameter("taskPhase", timesheet.getTaskPhase());
		if (q.list() != null && q.list().size() > 0) {
			System.out.println(q.list());
			return true;
		}
		else {
			return false;
		}

	}

	public static void save(Timesheet oldValue) {
		HibernateUtil hibenateUtil = new HibernateUtil();
		Session session = hibenateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		transaction.begin();
		session.save(oldValue);
		transaction.commit();
		/*Timesheet timesheet = (Timesheet) session.get(Timesheet.class, oldValue.getId());
		if (timesheet != null) {
			if (timesheet.getTaskNo() == oldValue.getTaskNo()
					&& timesheet.getTaskPhase().equals(oldValue.getTaskPhase())) {
				System.out.println("alrady edxists");
			}
			else {
				session.save(timesheet);
				transaction.commit();
			}
		}*/

	}
}
